package chen.bupt.mapreduce.feature;

import java.io.IOException;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import chen.bupt.constant.Constants;
import chen.bupt.text.StopWordUtil;
import chen.bupt.util.HDFSFileUtils;

/**
 * 提取特征词项
 * 
 * @author forrest
 * 
 */
public class FeatureExtractJob {
	private static String inputPath = Constants.TFIDF_PATH;
	private static String outputPath = Constants.FEATURE_TERM_PATH;

	public static class Map1 extends Mapper<LongWritable, Text, Text, Text> {
		private static final Text k = new Text("one");

		public void map(LongWritable key, Text value, Context context)
				throws IOException, InterruptedException {
			String values[] = value.toString().split("\\|");
			String feature = null;
			if (values == null || values.length < 2) {
				return;
			}
			for (int i = 1; i < values.length; i++) {
				if ("".equals(values[i])) {
					continue;
				}
				feature = values[i].split(";")[0];
				if (StopWordUtil.isSpecialTag(feature))
					return;
				if (feature != null) {
					context.write(k, new Text(feature));
				}
			}
		}
	}

	public static class Reduce1 extends Reducer<Text, Text, Text, NullWritable> {
		protected void reduce(Text key, Iterable<Text> values, Context context)
				throws IOException, InterruptedException {
			int featureNum = 0;
			StringBuffer sb = new StringBuffer();
			Set<String> set = new TreeSet<String>();
			for (Text value : values) {
				set.add(value.toString());
			}
			Iterator<String> ite = set.iterator();
			while (ite.hasNext()) {
				String term = ite.next();
				sb.append(term + ";");
				featureNum++;
			}
			context.write(new Text(sb.toString()), NullWritable.get());
			context.write(new Text("featureNum:" + featureNum), NullWritable
					.get());
		}
	}

	public static void main(String[] args) throws Exception {
		Configuration conf = new Configuration();
		Job job = new Job(conf, "featureExtract");
		job.setJarByClass(FeatureExtractJob.class);
		job.setMapperClass(Map1.class);
		job.setReducerClass(Reduce1.class);
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(Text.class);
		job.setNumReduceTasks(1);
		Path input = new Path(inputPath);
		Path output = new Path(outputPath);
		HDFSFileUtils.deleteFile(output, conf);
		FileInputFormat.addInputPath(job, input);
		FileOutputFormat.setOutputPath(job, output);
		System.exit(job.waitForCompletion(true) ? 0 : 1);

	}

}
